package listeners

import (
	"blockchains-aio/db"
	"github.com/gin-gonic/gin"
)

type criteria struct {
	Reposid string `uri:"reposid" binding:"required"`
}

var empty struct {
}

func RegisterReposRestful(router *gin.Engine) {

	router.GET("/repos", func(ctx *gin.Context) {
		reposArray := db.GetAllRepos()
		if reposArray == nil {
			ctx.JSON(200, empty)
			return
		}

		ctx.JSON(200, reposArray)
	})

	router.GET("/repos/:reposid", func(ctx *gin.Context) {
		var cr criteria
		if err := ctx.ShouldBindUri(&cr); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
			return
		}
		repos := db.GetReposById(cr.Reposid)
		if repos == nil {
			ctx.JSON(200, empty)
			return
		}
		ctx.JSON(200, repos)
	})

	router.POST("/repos", func(ctx *gin.Context) {
		//reposid, name, description, endpoint, username, password
		reposid := ctx.PostForm("reposid")
		name := ctx.PostForm("name")
		description := ctx.PostForm("description")
		endpoint := ctx.PostForm("endpoint")
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")

		if err := db.CreateRepos(reposid, name, description, endpoint, username, password); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
			return
		}

		ctx.JSON(200, empty)
	})

	router.POST("/repos/:reposid", func(ctx *gin.Context) {
		var cr criteria
		if err := ctx.ShouldBindUri(&cr); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
			return
		}
		name := ctx.PostForm("name")
		description := ctx.PostForm("description")
		endpoint := ctx.PostForm("endpoint")
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")

		if err := db.UpdateRepos(password, username, endpoint, name, description, cr.Reposid); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
		}
		ctx.JSON(200, empty)
	})

	router.DELETE("/repos/:reposid", func(ctx *gin.Context) {
		var cr criteria
		if err := ctx.ShouldBindUri(&cr); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
			return
		}
		if err := db.DelReposById(cr.Reposid); err != nil {
			ctx.JSON(400, gin.H{"msg": err.Error()})
		}
		ctx.JSON(200, empty)
	})
}
